package com.fdsc.erp.weixin.Utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * Created by Administrator on 2018-06-05.
 * 请求校验工具类
 */
public class SignUtil {
    //与开发模式接口配置信息中的token保持一直
    private static String token = "hzgyh";

    public static boolean checkSignature(String signature,String timestamp,String nonce){
        //对token timestamp和nonce按字典排序
        String[] paramArr = new String[]{token,timestamp,nonce};
        Arrays.sort(paramArr);

        //将排序后的结果拼接成一个字符串
        String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

        String ciphertext = null;
        //将 content 进行sha1加密
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.getBytes());
            ciphertext = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //将sha1加密后的字符串与sifnature进行对比

        return ciphertext !=null?ciphertext.equals(signature.toUpperCase()) : false;
    }
    /**
     * 将字节数组转换成十六进制字符串
     * @param bytearray
     * @return
     */
    private static String byteToStr(byte[] bytearray){
        String strDigest = "";
        for (int i=0;i<bytearray.length;i++){
            strDigest += byteToHexSte(bytearray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换成十六进制字符串
     * @param b
     * @return
     */
    private static String byteToHexSte(byte b) {
        char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        char[] ob = new char[2];
        ob[0] = Digit[(b>>>4) & 0X0F];
        ob[1] = Digit[b & 0X0F];

        String s = new String(ob);
        return s;
    }
}
